package com.fengmi.service.impl;

import com.fengmi.entity.SysPermission;
import com.fengmi.entity.SysRole;
import com.fengmi.entity.SysUser;
import com.fengmi.mapper.SysUserMapper;
import com.fengmi.service.UserService;
import com.fengmi.utils.security.JwtUtils;
import com.fengmi.utils.security.RsaUtils;
import com.fengmi.vo.InfoResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;

/**
 * Author: 施俊豪
 * Date: 2022/2/5 17:40
 * Note:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private SysUserMapper userMapper;
    
    /**
     * @Note : 登录         
     * @Date : 2022-02-05 22:59:16
     * @Author : 清酒吖
    */ 
    @Override
    public InfoResult login(SysUser user) {
        try {
            if(user == null){
                return new InfoResult(false,"用户名或者密码错误!!!","");
            }

            // 根据用户名查询用户
            SysUser userFromDB = userMapper.findUserByName(user.getAccount());

            if(userFromDB == null){
                return new InfoResult(false, "用户名或者密码错误!!!","");
            }

            // 校验密码
            BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
            // 明文密码和加密密码是否相等
            boolean matches = bCrypt.matches(user.getPassword(), userFromDB.getPassword());
            // 不相等,则返回用户名或者密码错误
            if (!matches){
                return new InfoResult(false,"用户名或者密码错误!!!","");
            }

            // 获取用户的角色和权限信息
            List<SysRole> rolesList = userMapper.findRolesByUserId(userFromDB.getUserId());
            String roles = "";
            for (SysRole sysRole : rolesList) {
                roles += sysRole.getRoleName()+",";
            }
            userFromDB.setRoles(roles);
            // 获取权限列表
            List<SysPermission> permissionList = userMapper.findPermissionByUserId(userFromDB.getUserId());
            String permissions = "";
            for (SysPermission sysPermission : permissionList) {
                permissions += sysPermission.getPermName()+",";
            }
            userFromDB.setPermissions(permissions);
            userFromDB.setPassword("");
            //颁发令牌
            //加载私钥
            String path = ResourceUtils.getFile("classpath:rsa").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(path);
            /**
             * userInfo:
             * privateKey: 私钥
             * expire: 过期时间
             */
            String jwt = JwtUtils.generateTokenExpireInMinutes(userFromDB/*payload*/, privateKey, 45);

            return new InfoResult(true,"success",jwt);
        } catch (Exception e) {
            e.printStackTrace();
            return new InfoResult(false,"用户名或者密码错误!!!","");
        }
    }
}
